package com.ghovos.usermangerpgdemo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ghovos.usermangerpgdemo.entity.MenuEntity;
import com.ghovos.usermangerpgdemo.entity.RoleEntity;
import com.ghovos.usermangerpgdemo.entity.RoleMenuEntity;
import com.ghovos.usermangerpgdemo.mapper.MenuMapper;
import com.ghovos.usermangerpgdemo.mapper.RoleMapper;
import com.ghovos.usermangerpgdemo.mapper.RoleMenuMapper;
import com.ghovos.usermangerpgdemo.service.MenuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liuli
 */
@Service
@AllArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements MenuService {

    private final RoleMenuMapper roleMenuMapper;
    private final MenuMapper menuMapper;
    private final RoleMapper roleMapper;

    @Override
    public List<MenuEntity> getAllMenuExt() {
        List<MenuEntity> menuEntities = menuMapper.selectList(null);
        // 1. 遍历 menuEntity
        menuEntities.forEach(menuEntity -> {
            MenuEntity extendList = this.getExtendList(menuEntity.getId());
            menuEntity.setRoleLists(extendList.getRoleLists());
        });

        return menuEntities;
    }

    @Override
    public MenuEntity getMenuExtById(Long id) {
        MenuEntity menuEntity = menuMapper.selectById(id);
        // 2. 通过中间表查询 关联的 roleIds
        MenuEntity extendList = this.getExtendList(id);
        menuEntity.setRoleLists(extendList.getRoleLists());
        return menuEntity;
    }

    @Override
    public boolean deleteByIdWithRole(Long id) {
        roleMenuMapper.delete(Wrappers.<RoleMenuEntity>lambdaQuery().eq(RoleMenuEntity::getMenuId, id));
        return this.removeById(id);

    }


    /**
     * 公用方法 , 连表查询 menu 拥有的 role list
     * @return 拥有 list 的 menu 实体
     */
    private MenuEntity getExtendList(Long menuId){
        MenuEntity menuEntity = new MenuEntity();
        // 1. 通过中间表查询 关联的 roleIds
        List<Long> roleIds = roleMenuMapper.selectList(
                Wrappers.<RoleMenuEntity>lambdaQuery()
                        .eq(RoleMenuEntity::getMenuId, menuId)
        ).stream().map(RoleMenuEntity::getRoleId).collect(Collectors.toList());

        // 2. 通过ids 查询 role的详情
        if (!roleIds.isEmpty()) {
            List<RoleEntity> roleEntities = roleMapper.selectBatchIds(roleIds);
            menuEntity.setRoleLists(roleEntities);
        }
        return menuEntity;
    }


}
